package com.cmpe451.nutty.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

public class ExceptionResolver implements HandlerExceptionResolver {
	private MyLogger logger = MyLogger.getLogger(getClass());

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		if (ex instanceof JsonResponseException) {
			logger.info("JsonResponseException::{0}", ex.getMessage());
			return handleJsonResponseException(request, response, (JsonResponseException) ex);
		} else if (ex instanceof HtmlResponseException) {
			logger.info("HtmlResponseException::{0}", ex.getMessage());
			return handleHtmlResponseException(request, response, (HtmlResponseException) ex);
		}

		MappingJacksonJsonView jsonView = new MappingJacksonJsonView();
		Map<String, Object> responseBody = new HashMap<String, Object>();

		response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

		responseBody.put("error", ex.getMessage());
		logger.error(ex, "uncaught exception::{0}", ex.getMessage());
		return new ModelAndView(jsonView, responseBody);
	}

	private ModelAndView handleJsonResponseException(HttpServletRequest req, HttpServletResponse resp, JsonResponseException e) {
		MappingJacksonJsonView jsonView = new MappingJacksonJsonView();

		resp.setStatus(e.getHttpStatus());

		Map<String, Object> responseBody = new HashMap<String, Object>();
		responseBody.put("error", e.getMessage());
		responseBody.put("errorCode", e.getErrorCode());
		return new ModelAndView(jsonView, responseBody);
	}

	private ModelAndView handleHtmlResponseException(HttpServletRequest req, HttpServletResponse resp, HtmlResponseException e) {
		resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("e", e);
		return new ModelAndView("internalError.view", model);
	}
}
